import axios from "axios";
import MockAdapter from "axios-mock-adapter";
import { MockConfig } from "../types/mock";
import { ApiResponse, ErrorCode } from "../types/api";
import users from "./data/users";
import auth from "./data/auth";

// Mock 配置
const mockConfig: MockConfig = {
  enable: import.meta.env.VITE_ENABLE_MOCK === "true" || import.meta.env.DEV,
  ignore: ["/api/file", "/api/upload"],
  timeout: 300,
};

/**
 * 创建一个Mock适配器
 */
export const createMock = (axiosInstance: typeof axios) => {
  if (!mockConfig.enable) {
    console.info("%c[Mock] Mock service is disabled", "color: #888");
    return null;
  }

  const mock = new MockAdapter(axiosInstance, {
    onNoMatch: "passthrough",
    delayResponse: mockConfig.timeout,
  });

  // 注册mock处理器
  setupMockHandlers(mock);

  return mock;
};

/**
 * 设置所有mock处理器
 */
function setupMockHandlers(mock: MockAdapter) {
  // 注册具体的Mock请求处理
  setupUserMocks(mock);
  setupAuthMocks(mock);

  console.info(
    "%c[Mock] Mock service is running",
    "color: #8bc34a; font-weight: bold"
  );
}

/**
 * 设置用户相关mock
 */
function setupUserMocks(mock: MockAdapter) {
  // 获取用户列表
  mock.onGet("/api/users").reply((config) => {
    const { page = 1, pageSize = 10 } = config.params || {};
    const start = (page - 1) * pageSize;
    const end = start + pageSize;
    const list = users.slice(start, end);
    const total = users.length;

    return [
      200,
      {
        code: ErrorCode.SUCCESS,
        data: {
          list,
          page,
          pageSize,
          total,
          totalPages: Math.ceil(total / pageSize),
        },
        message: "获取用户列表成功",
        success: true,
      },
    ];
  });

  // 获取用户详情
  mock.onGet(new RegExp("/api/users/\\w+")).reply((config) => {
    const id = config.url?.split("/").pop();
    const user = users.find((user) => user.id === id);

    if (!user) {
      return [
        404,
        {
          code: ErrorCode.NOT_FOUND,
          data: null,
          message: "用户不存在",
          success: false,
        },
      ];
    }

    return [
      200,
      {
        code: ErrorCode.SUCCESS,
        data: user,
        message: "获取用户详情成功",
        success: true,
      },
    ];
  });
  // 修改用户信息
  mock.onPut(new RegExp("/api/users/\\w+")).reply((config) => {
    const id = config.url?.split("/").pop();
    const userData = JSON.parse(config.data);
    const index = users.findIndex((user) => user.id === id);

    if (index === -1) {
      return [
        404,
        {
          code: ErrorCode.NOT_FOUND,
          data: null,
          message: "用户不存在",
          success: false,
        },
      ];
    }
    // 更新用户数据
    const updatedUser = { ...users[index], ...userData };
    users[index] = updatedUser;

    return [
      200,
      {
        code: ErrorCode.SUCCESS,
        data: updatedUser,
        message: "更新用户信息成功",
        success: true,
      },
    ];
  });

  // 删除用户
  mock.onDelete(new RegExp("/api/users/\\w+")).reply((config) => {
    const id = config.url?.split("/").pop();
    const index = users.findIndex((user) => user.id === id);

    if (index === -1) {
      return [
        404,
        {
          code: ErrorCode.NOT_FOUND,
          data: null,
          message: "用户不存在",
          success: false,
        },
      ];
    }

    // 删除用户
    users.splice(index, 1);

    return [
      200,
      {
        code: ErrorCode.SUCCESS,
        data: true,
        message: "删除用户成功",
        success: true,
      },
    ];
  });
}

/**
 * 设置认证相关mock
 */
function setupAuthMocks(mock: MockAdapter) {
  // 用户登录
  mock.onPost("/api/auth/login").reply((config) => {
    const { username, password } = JSON.parse(config.data);
    // 模拟登录验证
    if (
      (username === "admin" && password === "admin123") ||
      (username === "user" && password === "user123")
    ) {
      // 添加类型断言
      const user = auth.users.find((u: any) => u.username === username);
      if (!user) {
        return authFailedResponse();
      }

      return [
        200,
        {
          code: ErrorCode.SUCCESS,
          data: {
            user,
            token: `mock-token-${username}-${Date.now()}`,
          },
          message: "登录成功",
          success: true,
        },
      ];
    }
    return authFailedResponse();
  });

  // 获取当前用户信息
  mock.onGet("/api/auth/me").reply((config) => {
    // 检查授权头
    const authHeader = config.headers?.["Authorization"];
    if (!authHeader?.includes("Bearer ")) {
      return [
        401,
        {
          code: ErrorCode.UNAUTHORIZED,
          data: null,
          message: "未授权，请登录",
          success: false,
        },
      ];
    }

    // 模拟从token中解析用户信息
    const token = authHeader.replace("Bearer ", "");
    const username = token.split("-")[1]; // 简单提取
    // 添加类型断言
    const user = auth.users.find((u: any) => u.username === username);

    if (!user) {
      return [
        401,
        {
          code: ErrorCode.UNAUTHORIZED,
          data: null,
          message: "用户信息无效",
          success: false,
        },
      ];
    }

    return [
      200,
      {
        code: ErrorCode.SUCCESS,
        data: user,
        message: "获取用户信息成功",
        success: true,
      },
    ];
  });
}

/**
 * 认证失败响应
 */
function authFailedResponse(): [number, ApiResponse<null>] {
  return [
    401,
    {
      code: ErrorCode.UNAUTHORIZED,
      data: null,
      message: "用户名或密码错误",
      success: false,
    },
  ];
}

export default {
  config: mockConfig,
  create: createMock,
};
